const util = {}

util.dateFormat = (date, format) => {
  if (/\d{13}/.test(date)) {
    date = date - 0
  }
  ;
  try {
    if (date && date.length > 19) {
      date = date.substr(0, 19);
      date = date.replace(/\-/g, "/")
    }
  } catch (e) {
  }

  var dateObj = new Date(date);
  var o = {
    "Y+": dateObj.getFullYear(), //month
    "M+": dateObj.getMonth() + 1, //month
    "d+": dateObj.getDate(), //day
    "h+": dateObj.getHours(), //hour
    "m+": dateObj.getMinutes(), //minute
    "s+": dateObj.getSeconds(), //second
    "q+": Math.floor((dateObj.getMonth() + 3) / 3), //quarter
    "S": dateObj.getMilliseconds() //millisecond
  };

  if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (dateObj.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format))
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k])
        .length));
  }
  return format;
}
util.timeCountDown = (startTime, endTime) => {
  let count = Math.floor(new Date(startTime).getTime() - new Date(endTime).getTime()) / 1000

  let d = parseInt(count / (24 * 60 * 60))
  d = d < 10 ? "0" + d : d
  let h = parseInt(count / (60 * 60) % 24);
  h = h < 10 ? "0" + h : h
  let m = parseInt(count / 60 % 60);
  m = m < 10 ? "0" + m : m
  return d + '天' + h + '时' + m + '分'
}

util.getDeviceNumber = (value) => {
  if (value && value.length > 3) {
    value = value.substring(value.length - 3, value.length)
  }
  return value
}

//获取url后的参数  以对象返回
util.strToParams = (str) => {
  str = decodeURIComponent(str)
  str = str.includes('?') ? str.split('?')[1] : str
  var newparams = {}
  for (let item of str.split('&')) {
    newparams[item.split('=')[0]] = item.split('=')[1]
  }
  return newparams
}

util.formatNumber = (number, decimalPlaces = 2, round = false) => {
  if (round) {
    return Number(number.toFixed(decimalPlaces));
  } else {
    const multiplier = Math.pow(10, decimalPlaces);
    return Math.floor(number * multiplier) / multiplier;
  }
}
util.px2rpx = (value) => {
	if (!value) return 0
	const rpxValue = value / (uni.upx2px(100) / 100)
	return rpxValue;
}

util.phoneStar = (number) => {
	if (!number) return '';
	let len = number.substring(0, number.length - 4).length
	let str = ''
	for (let i = 0; i < len; i++) {
		str += '*'
	}
	return number.replace(/(.{3}).*(.{4})/, "$1****$2")
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
util.handleTree = (data, id, parentId, children) => {
  let config = {
    id: id || 'id',
    parentId: parentId || 'pid',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
 * 小程序比较版本信息
 * @param v1 当前版本
 * @param v2 进行比较的版本
 * @return boolen
 *
 */
util.compareVersion = (v1, v2) => {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)

	while (v1.length < len) {
		v1.push('0')
	}
	while (v2.length < len) {
		v2.push('0')
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i])
		const num2 = parseInt(v2[i])

		if (num1 > num2) {
			return 1
		} else if (num1 < num2) {
			return -1
		}
	}
	return 0
}

util.formatRichText = (html) => {
  if (!html) return '';
  let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi,
    '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
  return newContent;
}

export default util;
